/**
 * @(#) PertSaver.java
 */

package karabut.hw3;

import java.io.File;
import java.io.PrintWriter;
import java.util.HashSet;
import java.util.Set;

public class PertSaver {
	public void save(PertChart chart, String fileName) {
		PrintWriter writer = null;
		try {
			writer = new PrintWriter(new File(fileName));
			save(chart, writer);
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			if (writer != null) {
				try {
					writer.close();
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
			}
		}
	}
	
	private void save(PertChart chart, PrintWriter writer) {
		writer.println("digraph PERT {");
		writer.println("node[shape=rectangle,color=black]");
		writer.println("edge[color=black]");
		
		printNode(chart.getEndNode(), writer, new HashSet<String>());
		
		writer.println("}");
	}
	
	private void printNode(PertNode node, PrintWriter writer, Set<String> traversed) {
		if (traversed.contains(node.getTask())) {
			return;
		}
		
		traversed.add(node.getTask());
		for (PertNode pred : node.getPredcessors()) {
			printNode(pred, writer, traversed);
		}
		if (node.isOnCriticalPath()) {
			writer.println(getLabel(node) + "[color=red];");
		}
		for (PertNode pred : node.getPredcessors()) {
			if (pred.isOnCriticalPath() && node.isOnCriticalPath()) {
				writer.println(String.format("%s->%s[color=red];", getLabel(pred), getLabel(node)));
			}
			else {
				writer.println(String.format("%s->%s;", getLabel(pred), getLabel(node)));
			}
		}
	}
	
	private String getLabel(PertNode node) {
		return String.format("\"%s (%d days)\"", node.getTask(), node.getDuration());
	}

}
